package org.example;

import kotlin.Unit;
import kotlin.io.FilesKt;
import kotlin.jvm.internal.Intrinsics;
import kotlin.text.Charsets;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.letsPlot.GgplotKt;
import org.jetbrains.letsPlot.Stat;
import org.jetbrains.letsPlot.export.GgsaveKt;
import org.jetbrains.letsPlot.geom.geomDensity;
import org.jetbrains.letsPlot.intern.Options;
import org.jetbrains.letsPlot.intern.Plot;
import org.jetbrains.letsPlot.intern.PosKind;
import org.jetbrains.letsPlot.intern.layer.PosOptions;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.*;

public final class DemoUtil {

    public static Plot createPlot() {
        Random rand = new Random();
        int n = 200;
        String key = "x";
        ArrayList<Double> list = new ArrayList<>(n);

        for (int i = 0; i < n; ++i) {
            Double gaussian = rand.nextGaussian();
            list.add(gaussian);
        }

//        Map data = MapsKt.mapOf(TuplesKt.to(key, var18));
        Map<String, List<Double>> data = new HashMap<>();
        data.put(key, list);
        Plot plot = GgplotKt.letsPlot(data, (k) -> null);
        Number size = 2.0;
        Number alpha = 0.3;
        String fill = "green";
        String color = "dark-green";
        geomDensity density = new geomDensity(data, new Stat.density(),
                new PosOptions(PosKind.IDENTITY, Options.Companion.empty()), false,
                null, null, null, null, null,
                alpha, color, fill, null, size,
                null, null, null, null, null, null, null,
                densityMapping -> {
                    densityMapping.setX("x");
                    return Unit.INSTANCE;
                }
        );

        return plot.plus(density);
    }

    public static void save(Plot plot) {
        String path = GgsaveKt.ggsave(plot, "test.png", 2, null, null);
        System.out.println("path: " + path);
    }

    public static void openInBrowser(@NotNull String content) throws IOException {
        Intrinsics.checkNotNullParameter(content, "content");
        File dir = new File(System.getProperty("user.dir"), "lets-plot-images");
        dir.mkdir();
        File file = new File(dir.getCanonicalPath(), "my_plot.html");
        file.createNewFile();
        FilesKt.writeText(file, content, Charsets.UTF_8);
        Desktop.getDesktop().browse(file.toURI());
    }
}
